<template>
  <div class="goods-list-page">
    <h2>商品管理 / 商品列表</h2>
    <el-button type="primary" @click="handleAdd">添加</el-button>
    <el-table :data="goodsList" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="category" label="商品分类"></el-table-column>
      <el-table-column label="商品图片">
        <template #default="scope">
          <img v-if="scope.row.imageUrl" :src="scope.row.imageUrl" alt="商品图片" style="width: 60px; height: 60px;">
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column prop="stock" label="库存"></el-table-column>
      <el-table-column label="是否上架">
        <template #default="scope">
          <el-switch v-model="scope.row.isOnSale" @change="handleSwitch(scope.row, 'isOnSale')"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否热销单品">
        <template #default="scope">
          <el-switch v-model="scope.row.isHot" @change="handleSwitch(scope.row, 'isHot')"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否今日上新">
        <template #default="scope">
          <el-switch v-model="scope.row.isNewToday" @change="handleSwitch(scope.row, 'isNewToday')"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否精品优选">
        <template #default="scope">
          <el-switch v-model="scope.row.isPremium" @change="handleSwitch(scope.row, 'isPremium')"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="100rpx">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row.id)">删除</el-button>
          <el-button type="text" @click="handleSetSku(scope.row)">设置 sku</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑商品弹窗 -->
    <el-dialog title="添加商品" :visible.sync="dialogVisible" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-input v-model="form.category"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="imageUrl">
          <el-upload
            action="#"
            :on-success="handleImageUpload"
            :file-list="fileList"
            :auto-upload="true"
            accept="image/*"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <img v-if="form.imageUrl" :src="form.imageUrl" alt="预览" style="width: 100px; height: 100px; margin-top: 10px;">
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input type="number" v-model="form.price"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input type="number" v-model="form.stock"></el-input>
        </el-form-item>
        <el-form-item label="是否上架" prop="isOnSale">
          <el-switch v-model="form.isOnSale"></el-switch>
        </el-form-item>
        <el-form-item label="是否热销单品" prop="isHot">
          <el-switch v-model="form.isHot"></el-switch>
        </el-form-item>
        <el-form-item label="是否今日上新" prop="isNewToday">
          <el-switch v-model="form.isNewToday"></el-switch>
        </el-form-item>
        <el-form-item label="是否精品优选" prop="isPremium">
          <el-switch v-model="form.isPremium"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设置 sku 弹窗 -->
    <el-dialog title="设置 sku" :visible.sync="skuDialogVisible" width="400px">
      <el-form :model="skuForm" :rules="skuRules" ref="skuFormRef" label-width="100px">
        <el-form-item label="SKU 名称" prop="skuName">
          <el-input v-model="skuForm.skuName"></el-input>
        </el-form-item>
        <el-form-item label="SKU 价格" prop="skuPrice">
          <el-input type="number" v-model="skuForm.skuPrice"></el-input>
        </el-form-item>
        <el-form-item label="SKU 库存" prop="skuStock">
          <el-input type="number" v-model="skuForm.skuStock"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="skuDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSku">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  setup() {
    // 模拟商品列表数据
    const goodsList = ref([
      {
        id: 1,
        name: '2310大礼包',
        category: '第三方 1111111111111',
        imageUrl: 'https://picsum.photos/60/60?random=1',
        price: 99,
        stock: 100,
        isOnSale: true,
        isHot: false,
        isNewToday: false,
        isPremium: false,
      },
      {
        id: 2,
        name: '问雯家的薯片',
        category: '薯片膨化',
        imageUrl: 'https://picsum.photos/60/60?random=2',
        price: 53,
        stock: 10000,
        isOnSale: true,
        isHot: false,
        isNewToday: true,
        isPremium: true,
      },
      {
        id: 3,
        name: '乐事（Lay\'s）薯片',
        category: '薯片膨化',
        imageUrl: 'https://picsum.photos/60/60?random=3',
        price: 49,
        stock: 10000,
        isOnSale: true,
        isHot: false,
        isNewToday: true,
        isPremium: true,
      },
      {
        id: 4,
        name: '麦酥园沙琪玛',
        category: '饼干糕点',
        imageUrl: 'https://picsum.photos/60/60?random=4',
        price: 39,
        stock: 10000,
        isOnSale: true,
        isHot: false,
        isNewToday: true,
        isPremium: true,
      },
      {
        id: 5,
        name: '友臣肉松棒',
        category: '饼干糕点',
        imageUrl: 'https://picsum.photos/60/60?random=5',
        price: 39,
        stock: 10000,
        isOnSale: true,
        isHot: false,
        isNewToday: true,
        isPremium: true,
      },
    ]);

    // 弹窗相关状态
    const dialogVisible = ref(false);
    const skuDialogVisible = ref(false);

    // 表单数据
    const form = reactive({
      id: '',
      name: '',
      category: '',
      imageUrl: '',
      price: 0,
      stock: 0,
      isOnSale: false,
      isHot: false,
      isNewToday: false,
      isPremium: false,
    });

    const skuForm = reactive({
      skuName: '',
      skuPrice: 0,
      skuStock: 0,
    });

    // 当前操作的商品（用于设置 sku）
    const currentGoods = ref(null);

    // 文件列表（图片上传）
    const fileList = ref([]);

    // 表单验证规则
    const rules = reactive({
      name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
      category: [{ required: true, message: '请输入商品分类', trigger: 'blur' }],
      price: [
        { required: true, message: '请输入价格', trigger: 'blur' },
        { type: 'number', message: '价格必须为数字', trigger: 'blur' },
      ],
      stock: [
        { required: true, message: '请输入库存', trigger: 'blur' },
        { type: 'number', message: '库存必须为数字', trigger: 'blur' },
      ],
    });

    const skuRules = reactive({
      skuName: [{ required: true, message: '请输入 SKU 名称', trigger: 'blur' }],
      skuPrice: [
        { required: true, message: '请输入 SKU 价格', trigger: 'blur' },
        { type: 'number', message: 'SKU 价格必须为数字', trigger: 'blur' },
      ],
      skuStock: [
        { required: true, message: '请输入 SKU 库存', trigger: 'blur' },
        { type: 'number', message: 'SKU 库存必须为数字', trigger: 'blur' },
      ],
    });

    // 表单引用
    const formRef = ref(null);
    const skuFormRef = ref(null);

    // 是否为编辑状态
    const isEdit = ref(false);

    // 处理添加按钮点击
    const handleAdd = () => {
      isEdit.value = false;
      form.id = '';
      form.name = '';
      form.category = '';
      form.imageUrl = '';
      form.price = 0;
      form.stock = 0;
      form.isOnSale = false;
      form.isHot = false;
      form.isNewToday = false;
      form.isPremium = false;
      fileList.value = [];
      dialogVisible.value = true;
    };

    // 处理编辑按钮点击
    const handleEdit = (row) => {
      isEdit.value = true;
      form.id = row.id;
      form.name = row.name;
      form.category = row.category;
      form.imageUrl = row.imageUrl;
      form.price = row.price;
      form.stock = row.stock;
      form.isOnSale = row.isOnSale;
      form.isHot = row.isHot;
      form.isNewToday = row.isNewToday;
      form.isPremium = row.isPremium;
      fileList.value = row.imageUrl ? [{ url: row.imageUrl }] : [];
      dialogVisible.value = true;
    };

    // 处理开关状态变化（仅前端提示，无实际接口请求）
    const handleSwitch = (row, prop) => {
      ElMessage.success(`${prop}状态已更新`);
    };

    // 处理图片上传成功（仅前端显示，无实际接口请求）
    const handleImageUpload = (response, file) => {
      form.imageUrl = URL.createObjectURL(file.raw);
    };

    // 提交商品表单（前端增删改）
    const submitForm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          if (isEdit.value) {
            // 编辑操作，更新现有商品
            const index = goodsList.value.findIndex((item) => item.id === form.id);
            if (index !== -1) {
              goodsList.value[index] = { ...form };
              ElMessage.success('编辑成功');
            }
          } else {
            // 添加操作，生成新 ID 并添加商品
            form.id = new Date().getTime();
            goodsList.value.push({ ...form });
            ElMessage.success('添加成功');
          }
          dialogVisible.value = false;
        }
      });
    };

    // 处理删除按钮点击（前端删除）
    const handleDelete = (id) => {
      ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
        type: 'warning',
      }).then(() => {
        const index = goodsList.value.findIndex((item) => item.id === id);
        if (index !== -1) {
          goodsList.value.splice(index, 1);
          ElMessage.success('删除成功');
        }
      }).catch(() => {
        ElMessage.info('已取消删除');
      });
    };

    // 处理设置 sku 按钮点击
    const handleSetSku = (row) => {
      currentGoods.value = row;
      skuForm.skuName = '';
      skuForm.skuPrice = 0;
      skuForm.skuStock = 0;
      skuDialogVisible.value = true;
    };

    // 提交 SKU 表单（仅前端提示，无实际接口请求）
    const submitSku = () => {
      skuFormRef.value.validate((valid) => {
        if (valid) {
          ElMessage.success(`为商品【${currentGoods.value.name}】设置 SKU 成功`);
          skuDialogVisible.value = false;
        }
      });
    };

    return {
      goodsList,
      dialogVisible,
      skuDialogVisible,
      form,
      skuForm,
      currentGoods,
      fileList,
      rules,
      skuRules,
      formRef,
      skuFormRef,
      isEdit,
      handleAdd,
      handleEdit,
      handleSwitch,
      handleImageUpload,
      submitForm,
      handleDelete,
      handleSetSku,
      submitSku,
    };
  },
};
</script>

<style scoped>
.goods-list-page {
  padding: 20px;
}
</style>